package com.lottery.ruok.lottrey.dialog;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.chat.RongCloudChatManager;
import com.lottery.ruok.lottrey.chat.model.prize.message.PrizeMessage;
import com.lottery.ruok.lottrey.chat.model.redpacket.message.sendRedPacketMessage.RedPacketMessage;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetProfileRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GivePrizeRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.SendGiftRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.WithdrawalsRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GetProfileResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.OrderCancelResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.SendGiftResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.WithdrawalsResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imlib.IFwLogCallback;
import ui.ItemPasswordLayout;
import utils.StringUtils;
import utils.Utils;

/**
 * Created by ASUS on 2017/8/2.
 */

public class PasswordDialog extends DialogFragment {


    public static final String TYPE = "type";
    public static final String POCKET_TYPE = "pocketType";
    public static final String AMOUNT = "amount";
    public static final String PER_AMOUNT = "per_amount";
    public static final String NUMBERS = "numbers";
    public static final String DESC = "desc";
    public static final String TO_USER = "to_user";
    public static final String TO_USER_NAME = "to_user_name";
    public static final String TARGET_ID = "target_id";
    public static final String conversationType = "conversationType";
    @BindView(R.id.password)
    ItemPasswordLayout password;
    @BindView(R.id.close)
    ImageView close;

    private int mType = 0;//0是取现,1是发红包,2是打赏
    private int pocketType;
    private double totalMoney;
    private double singlePacketMoney;
    private int packetNum;
    private String desc;
    private String toUserId;
    private String targetId;
    private String toUserAvatar;
    private io.rong.imlib.model.UserInfo toUser;
    private String toUserName;
    private String myConversionType;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    private void init() {
        Bundle arguments = getArguments();
        if (arguments != null) {
            mType = arguments.getInt(TYPE);
            pocketType = arguments.getInt(POCKET_TYPE);
            totalMoney = arguments.getDouble(AMOUNT);
            singlePacketMoney = arguments.getDouble(PER_AMOUNT);
            packetNum = arguments.getInt(NUMBERS);
            desc = arguments.getString(DESC);
            targetId = arguments.getString(TARGET_ID);
            toUser = arguments.getParcelable(TO_USER);
            toUserName = arguments.getString(TO_USER_NAME);
            myConversionType = arguments.getString(conversationType);

        }
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //自定义对话框样式
        View v = inflater.inflate(R.layout.password_dialog_layout, null);

        ButterKnife.bind(this, v);

        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().setCanceledOnTouchOutside(false);

        getDialog().setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialogInterface) {
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(password.getEditText(), InputMethodManager.SHOW_IMPLICIT);
            }
        });

        password.setInputCompleteListener(new ItemPasswordLayout.InputCompleteListener() {
            @Override
            public void inputComplete() {
                switch (mType) {
                    case 0:
                        doWithdraw();
                        break;
                    case 1:
                        sendRedPacket();
                        break;
                    case 2:
                        givePrize();
                        break;
                }
            }

            @Override
            public void inputing() {

            }
        });

        return v;
    }

    private void updateAccount() {
        RetrofitBase.getRetrofit().create(GetProfileRequest.class).getResult(UserInfo.getToken())
                .compose(RxHelper.<GetProfileResponse>handleResultReConnection())
                .subscribe(new RxSubscribe<GetProfileResponse>(getActivity()) {
                    @Override
                    protected void _onNext(final GetProfileResponse getProfileResponse) {
                        Common.today_profit = getProfileResponse.getToday_lostwin();
                        UserInfo.setAccount(getProfileResponse.getUser().getAccount());
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });

    }

    private void givePrize() {
        String name="";
        if (com.lottery.ruok.lottrey.utils.StringUtils.isNotEmpty(toUserName)){
            name=toUserName;
        }else {
            name=toUser.getName();
        }
        RetrofitBase.getRetrofit().create(GivePrizeRequest.class)
                .getResult(UserInfo.getToken(), UserInfo.getUsername(), name, totalMoney + "", password.getStrPassword())
                .compose(RxHelper.<OrderCancelResponse>handleResult())
                .subscribe(new RxSubscribe<OrderCancelResponse>(getActivity()) {
                    @Override
                    protected void _onNext(OrderCancelResponse givePrizeResponse) {
                        Utils.showToast(givePrizeResponse.getMsg());
                        PrizeMessage prizeMessage = new PrizeMessage();
                        prizeMessage.setMoney(totalMoney);
                        // prizeMessage.setMsgId(Long.parseLong(messageId));
                       // prizeMessage.setDate(StringUtils.formatTime(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
                        prizeMessage.setDate(""+System.currentTimeMillis());
                        prizeMessage.setSendUserId(UserInfo.getMyUserId());
                        prizeMessage.setSendUserAvatar(UserInfo.getAvatar());
                        prizeMessage.setSendUserNickname(UserInfo.getNickname());
                        prizeMessage.setReceiveUserId(toUser.getUserId());
                        prizeMessage.setReceiveUserNickname(toUser.getName());
                        prizeMessage.setReceiveUserAvatar(""+toUser.getPortraitUri());
                        prizeMessage.setTargetId(""+UserInfo.getRoomId());
                       /* prizeMessage.setSendUserId(UserInfo.getMyUserId());
                        prizeMessage.setReceiveUserId(toUser.getUserId());*/
                       if (myConversionType.equals("chatroom")){
                           RongCloudChatManager.sendMessage(targetId, prizeMessage);
                       }else if (myConversionType.equals("private")){
                           RongCloudChatManager.sendMessagePrivate(targetId, prizeMessage);
                       }

                        updateAccount();
                        dismissAllowingStateLoss();
                        getActivity().finish();
                    }

                    @Override
                    protected boolean showDialog() {
                        return true;
                    }
                });
    }

    private void sendRedPacket() {
        String name="";
        if (com.lottery.ruok.lottrey.utils.StringUtils.isNotEmpty(toUserName)){
            name=toUserName;
        }else {
            if (toUser!=null){
                name=toUser.getName();
            }
        }
        RetrofitBase.getRetrofit().create(SendGiftRequest.class).getResult(UserInfo.getToken(),
                pocketType,
                singlePacketMoney + "",
                Utils.saveTwoFormat(totalMoney),
                packetNum,
                desc,
                UserInfo.getUsername(),
                name,
                targetId,
                password.getStrPassword())
                .compose(RxHelper.<SendGiftResponse>handleResult())
                .subscribe(new RxSubscribe<SendGiftResponse>(getActivity()) {
                    @Override
                    protected void _onNext(SendGiftResponse sendGiftResponse) {
                        Utils.showToast(sendGiftResponse.getMsg());
                        //发送红包消息
                        RedPacketMessage redPacketMessage = new RedPacketMessage();
                        redPacketMessage.setContent(sendGiftResponse.getDesc());
                        redPacketMessage.setMsgId(sendGiftResponse.getGift_id());
                        redPacketMessage.setType(pocketType);
                        redPacketMessage.setDate(StringUtils.formatTime(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
                        redPacketMessage.setTargetId(targetId);

                        redPacketMessage.setSendUserId(UserInfo.getMyUserId());
                        redPacketMessage.setSendUserNickname(UserInfo.getNickname());
                        redPacketMessage.setSendUserAvatar(UserInfo.getAvatar());
                        if (com.lottery.ruok.lottrey.utils.StringUtils.isNotEmpty(toUserId)){
                            redPacketMessage.setReceiveUserId(toUserId);
                        }
                       // RongCloudChatManager.sendMessage(targetId + "", redPacketMessage);
                        if (StringUtils.isEmpty(toUserName)){
                            RongCloudChatManager.sendMessage(targetId, redPacketMessage);
                        }else {
                            RongCloudChatManager.sendMessagePrivate(targetId, redPacketMessage);
                        }

                        dismissAllowingStateLoss();
                        getActivity().finish();
                    }

                    @Override
                    protected boolean showDialog() {
                        return true;
                    }
                });
    }

    private void doWithdraw() {
        RetrofitBase.getRetrofit().create(WithdrawalsRequest.class).getResult(UserInfo.getToken(),
                getArguments().getString("money"),
                password.getStrPassword())
                .compose(RxHelper.<WithdrawalsResponse>handleResult())
                .subscribe(new RxSubscribe<WithdrawalsResponse>(getActivity()) {
                    @Override
                    protected void _onNext(WithdrawalsResponse withdrawalsResponse) {
                        Utils.showToast(withdrawalsResponse.getMsg());

                        dismissAllowingStateLoss();
                        getActivity().finish();
                    }

                    @Override
                    protected boolean showDialog() {
                        return true;
                    }
                });
    }

    @OnClick(R.id.close)
    public void onViewClicked() {
        dismissAllowingStateLoss();
    }

    @Override
    public void onResume() {
        super.onResume();

        Window window = getDialog().getWindow();
//        window.setLayout(Utils.getWindowDisplay(getActivity()).widthPixels, Utils.getWindowDisplay(getActivity()).heightPixels);
        window.setLayout(Utils.getWindowDisplay(getActivity()).widthPixels - Utils.dip2px(getActivity(), 20), Utils.dip2px(getActivity(), 200));
    }
}
